package com.qujia.station.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.PageDomain;
import com.qujia.common.core.page.TableSupport;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.sql.SqlUtil;
import com.qujia.station.domain.vo.EnterpriseAndStationVo;
import com.qujia.station.mapper.SysUserInviteInfoMapper;
import com.qujia.station.service.GzhMenuService;
import com.qujia.station.service.IStationService;
import com.qujia.station.service.ISysUserInviteInfoService;
import com.qujia.system.domain.QrCodeRes;
import com.qujia.system.domain.dto.SysUserInviteInfoDetailResDto;
import com.qujia.system.domain.dto.SysUserInviteInfoResDto;
import com.qujia.system.domain.form.SysUserInviteInfoDetailReqForm;
import com.qujia.system.domain.form.SysUserInviteInfoReqForm;
import com.qujia.system.domain.vo.SysUserInviteInfoListResVo;
import com.qujia.system.domain.vo.SysUserInviteQrCodeResVo;
import com.qujia.system.mapper.SysDictDataMapper;
import com.qujia.system.mapper.SysEnterpriseUserMapper;
import com.qujia.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class StaffInviteServiceImpl implements ISysUserInviteInfoService {

    public static final String DIC_TYPE_STAFF_SETTING = "staff_setting";

    public static final String DIC_LABEL_STAFF_ROLE_ID = "staff_role_id";

    @Autowired
    private SysEnterpriseUserMapper enterpriseUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserInviteInfoMapper sysUserInviteInfoMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private IStationService stationService;

    @Autowired
    private GzhMenuService gzhMenuService;

    @Override
    public SysUserInviteQrCodeResVo getUserInviteQrCodeInfo(Long userId) {
        SysUserInviteQrCodeResVo staffInviteQrCodeResVo = new SysUserInviteQrCodeResVo();
        // 获取当前登录的用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long enterpriseId = loginUser.getUser().getEnterpriseId();

        // 查询是否已经已经有了二维码
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        if (null == sysUser) {
            throw new CustomException("员工信息不存在！");
        }
        if (StringUtils.isNotBlank(sysUser.getInviteQrcodeUrl())) {
            try {
                QrCodeRes qrCodeRes = JSONObject.parseObject(sysUser.getInviteQrcodeUrl(), QrCodeRes.class);
                if (null == qrCodeRes) {
                    throw new CustomException("员工推荐二维码获取失败！json解析异常，qrCodeRes" + sysUser.getInviteQrcodeUrl());
                }
                staffInviteQrCodeResVo.setQrCodeUrl(qrCodeRes.getQrCodeUrl());
                staffInviteQrCodeResVo.setUrl(qrCodeRes.getUrl());
                staffInviteQrCodeResVo.setUserId(userId);
                return staffInviteQrCodeResVo;
            } catch (Exception e) {
                log.error("二维码获取失败：" + e.getMessage());
            }
        }

//        // 根据油企id 获取公众号gzh_app_id,gzh_app_secret
//        SysEnterpriseUser enterprise = enterpriseUserMapper.selectSysEnterpriseUserById(enterpriseId);
//        if (null == enterprise) {
//            throw new CustomException("油企信息不存在！");
//        }
//
//        // 调微信获取二维码
//        Token token = WxUserUtil.getToken(enterprise.getGzhAppId(), enterprise.getGzhAppSecret());
        String token = gzhMenuService.getGzhToken(enterpriseId);
        if (null == token) {
            throw new CustomException("微信授权失败！");
        }
        JSONObject target = new JSONObject();
        target.put("enterpriseId", enterpriseId);
        target.put("userId", userId);
        QrCodeRes qrCodeRes = WeiXinUserUtil.getQrcode(token, JSONObject.toJSONString(target), true, null);
        if (null == qrCodeRes) {
            throw new CustomException("获取微信生成二维码失败！");
        }
        //保存二维码
        SysUser sysUserUpdate = new SysUser();
        sysUserUpdate.setUserId(userId);
        sysUserUpdate.setInviteQrcodeUrl(JSONObject.toJSONString(qrCodeRes));
        sysUserUpdate.setUpdateTime(new Date());
        sysUserUpdate.setUpdateBy(SecurityUtils.getUsername());
        sysUserMapper.updateUser(sysUserUpdate);
        staffInviteQrCodeResVo.setQrCodeUrl(qrCodeRes.getQrCodeUrl());
        staffInviteQrCodeResVo.setUrl(qrCodeRes.getUrl());
        staffInviteQrCodeResVo.setUserId(userId);
        return staffInviteQrCodeResVo;
    }

    @Override
    public SysUserInviteInfoListResVo getSysUserInviteInfoListPage(SysUserInviteInfoReqForm sysUserInviteInfoReqForm) {
        SysUserInviteInfoListResVo resVo = new SysUserInviteInfoListResVo();
        // 获取当前登录的用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        if (UserConstants.LEVEL_TWO.equals(sysUser.getLevelId())) {
            sysUserInviteInfoReqForm.setEnterpriseId(sysUser.getEnterpriseId());
        }
        if (UserConstants.LEVEL_THREE.equals(sysUser.getLevelId())) {
            sysUserInviteInfoReqForm.setEnterpriseId(sysUser.getEnterpriseId());
            sysUserInviteInfoReqForm.setStationId(sysUser.getStationId());
        }
        if (SecurityUtils.isPartner()) {
            EnterpriseAndStationVo itemIds = stationService.getItemIds(sysUser);
            sysUserInviteInfoReqForm.setStationIds(itemIds.getStationIds());
        }
        // 根据员工列表查询逻辑加上的
        sysUserInviteInfoReqForm.setRoleId(dictDataMapper.selectDictValue(DIC_TYPE_STAFF_SETTING, DIC_LABEL_STAFF_ROLE_ID));
        sysUserInviteInfoReqForm.setUserLeval(UserConstants.LEVEL_THREE);
        startPage();
        List<SysUserInviteInfoResDto> resDtos = sysUserInviteInfoMapper.selectSysUserInviteInfo(sysUserInviteInfoReqForm);
        PageHelper.clearPage();
        resVo.setUserInviteInfos(resDtos);
        resVo.setCountInvite(sysUserInviteInfoMapper.countSysUserInviteInfo(sysUserInviteInfoReqForm));
        return resVo;
    }

    @Override
    public List<SysUserInviteInfoResDto> getSysUserInviteInfoList(SysUserInviteInfoReqForm sysUserInviteInfoReqForm) {
        // 获取当前登录的用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        if (UserConstants.LEVEL_TWO.equals(sysUser.getLevelId())) {
            sysUserInviteInfoReqForm.setEnterpriseId(sysUser.getEnterpriseId());
        }
        if (UserConstants.LEVEL_THREE.equals(sysUser.getLevelId())) {
            sysUserInviteInfoReqForm.setEnterpriseId(sysUser.getEnterpriseId());
            sysUserInviteInfoReqForm.setStationId(sysUser.getStationId());
        }
        sysUserInviteInfoReqForm.setRoleId(dictDataMapper.selectDictValue(DIC_TYPE_STAFF_SETTING, DIC_LABEL_STAFF_ROLE_ID));
        sysUserInviteInfoReqForm.setUserLeval(UserConstants.LEVEL_THREE);
        return sysUserInviteInfoMapper.selectSysUserInviteInfo(sysUserInviteInfoReqForm);
    }

    @Override
    public List<SysUserInviteInfoDetailResDto> getSysUserInviteInfoDetailList(SysUserInviteInfoDetailReqForm sysUserInviteInfoDetailReqForm) {
        if (null == sysUserInviteInfoDetailReqForm.getUserId()) {
            throw new CustomException("员工id不能为空！");
        }
        List<SysUserInviteInfoDetailResDto> resDtos = new ArrayList<>();
        List<Long> appUserIds = sysUserInviteInfoMapper.selectAppUserIdBySysUserId(sysUserInviteInfoDetailReqForm.getUserId());
        if (null == appUserIds || appUserIds.size() == 0)
            return resDtos;
        sysUserInviteInfoDetailReqForm.setAppUserIds(appUserIds);
        startPage();
        resDtos = sysUserInviteInfoMapper.selectSysUserInviteAppUserInfo(sysUserInviteInfoDetailReqForm);
        PageHelper.clearPage();
        return resDtos;
    }

    private void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (!Objects.isNull(pageNum) && !Objects.isNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }
}
